package read1;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;

public class HuyaPage extends Pages{
	static String huyaURL = "http://www.huya.com/1976196156";
	static String URLtoTest = "http://www.huya.com/world2017";
	private static final String URLHead = "http://www.huya.com/";
	private Logger log = Logger.getLogger(this.getClass());
	
	private List<WebElement> messages = null;
	
	@Override
	protected String getURL() {
		return huyaURL;
	}

	@Override
	protected String getURL(String partURL) {
		return URLHead + partURL;
	}
	
	public HuyaPage() {super();}
	public HuyaPage(String partURL) {super(partURL);}
	
	public void closeFlash(){
		JavascriptExecutor js = (JavascriptExecutor) driver;
		js.executeScript("return document.getElementById('videoContainer').remove();");
		log.info("flash closed");
	}
	
	public void test() {
		closeFlash();
		for (int i=0 ; i<5 ; i++) {
			sleep(5000);
			getNewMessage();
		}
	}
	
	public List<WebElement> getMessageElements() {
		By messages = By.className("J_msg");
		return driver.findElements(messages);
	}
	
	public List<String> getNewMessage(List<WebElement> newMessages, List<WebElement> oldMessages) {
		String idNumNewStr = newMessages.get(newMessages.size()-1).getAttribute("data-id");
		String idNumOldStr = "";
		if(oldMessages==null||oldMessages.size()==0) {
			idNumOldStr = "0";
		} else {
			try {
				idNumOldStr = oldMessages.get(oldMessages.size()-1).getAttribute("data-id");				
			} catch (Exception e) {
				log.error("exception on get idNumOldStr");
			}
		}
		int idNumNew = 0;
		int idNumOld = 0;
		try {
			idNumNew = Integer.parseInt(idNumNewStr);
			idNumOld = Integer.parseInt(idNumOldStr);
		} catch (NumberFormatException e) {
		    e.printStackTrace();
		}
//		log.info("old data-id: " + idNumOld);
//		if(idNumOld!=0) {
//			log.info("old message.last.innerHTML: " + oldMessages.get(oldMessages.size()-1).getAttribute("innerHTML"));
//		}
		//log.info("new data-id: " + idNumNew);
		//log.info("old message.last.innerHTML: " + newMessages.get(newMessages.size()-1).getAttribute("innerHTML"));
		int dif = idNumNew - idNumOld;
		if (dif > (newMessages.size()-1)) {
			dif = newMessages.size()-1;
		}
		log.info("there are how many new message: " + dif);
		
		//由id的差值获取新的message
		if(dif > 0) {
			List<String> result = new ArrayList<String>();
			int id = 0;
			for (int i=0 ; i<dif ; i++) {
				id = newMessages.size() - dif + i;
				//log.info("获取第 " + id + " 项元素的文本");
				result.add(getTextFromElement(newMessages.get(id)));
			}
			return result;
		}
		return null;
	}
	
	public List<String> getNewMessage() {
		List<WebElement> oldMessages = messages;
		//log.info("oldMessages.size(): " + ((oldMessages==null)?0:oldMessages.size()));
		messages = getMessageElements();
		//log.info("messages.size(): " + messages.size());
		return getNewMessage(messages, oldMessages);
	}

	public String getTextFromElement(WebElement w) {
		//log.info("innerHTML: " + w.getAttribute("innerHTML"));
		String name = "";
		String content = "";
		String action = "";
		try {
			WebElement w2 = w.findElement(By.xpath("./p"));
			log.info("is ./p");
			if(w2.getAttribute("class").contains("send")) {
				action = "送了";
				String gift = w.findElement(By.cssSelector(".send-to")).getAttribute("innerHTML");
				content = gift.substring(gift.lastIndexOf(">")) + "个礼物";
			} else {
				return w2.getAttribute("innerHTML");
			}
		} catch (NoSuchElementException e) {
		}

		try {
			name = w.findElement(By.cssSelector(".name")).getAttribute("innerHTML");
		} catch (NoSuchElementException e) {}
		try {
			WebElement w2 = w.findElement(By.xpath(".//*[@class = 'text-content']"));
			content = w2.getAttribute("innerHTML");
//			String s = w2.getAttribute("innerText");
		} catch (NoSuchElementException e) {
			try {
				WebElement w2 = w.findElement(By.cssSelector(".msg"));
				content = w2.getAttribute("innerHTML");
			}catch (NoSuchElementException e2) {
			}
		} catch (Exception e) {
		}
		
		try {
			WebElement w2 = w.findElement(By.cssSelector(".noble-enter-text"));
			action = w2.getAttribute("innerHTML").replace("&nbsp;", "");
		} catch (Exception e) {
			if (!name.isEmpty()&&!content.isEmpty()&&action.isEmpty()) {
				action = "说，";
			}
		}
		return name + action + content;
	}
	
	public void read(Reader reader) {
		log.info("start read");
		closeFlash();
		
		Date time = new Date();
		Date time2 = time;
		while(true) {
			time2 = new Date();
			int timeDif = (int) (time2.getTime() - time.getTime());
			time = time2;
			//log.info("time dif: " + timeDif);
			if(timeDif < 5000) {
				sleep(5000 - timeDif);
			}			
			reader.read(getTreadedList(getNewMessage()));
		}
	}
	
	List<String> getTreadedList(List<String> beforeList) {
		if(beforeList!=null) {
			List<String> result = new ArrayList<String>();
			for(String s: beforeList) {
				result.add(getTreadedSingleString(s));
			}
			return result;
		} else {
			return null;
		}
	}
	
	String getTreadedSingleString(String before) {
        String regEx = "<img[^>][\\s\\S]*?>"; //定义script的正则表达式 
        Pattern p_script = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE); 
        Matcher m_script = p_script.matcher(before); 
        String after = m_script.replaceAll(""); //过滤script标签 
        after.replace(" ", "");
        log.info("String is: " + after);
        return after;
	}
	
//	public List<String> getMessages(){
//		List<WebElement> ws = getMessageElements();
//		List<String> mstring = new ArrayList<String>();
//		for (int i=0 ; i<ws.size() ; i++) {
//			WebElement w = ws.get(i);
//			if (w.getAttribute("innerHTML").contains("<span class=\"text-content\">")) {
//				String s = w.findElement(By.xpath(".//*[@class = 'text-content']")).getAttribute("innerText");
//				System.out.println("s = " + s);
//				mstring.add(s);
//			} else {
////				mstring.add(ws.get(i).getAttribute("innerHTML"));
//			}
//		}
//		return mstring;
//	}

	
//	public List<String> getNewMessage(List<WebElement> oldMessages) {
//		List<WebElement> newEs = getMessageElements();
//		String idNumNewStr = newEs.get(newEs.size()-1).getAttribute("data-id");
//		String idNumOldStr = oldMessages.get(oldMessages.size()-1).getAttribute("data-id");
//		int idNumNew = 0;
//		int idNumOld = 0;
//		try {
//			idNumNew = Integer.parseInt(idNumNewStr);
//			idNumOld = Integer.parseInt(idNumOldStr);
//		} catch (NumberFormatException e) {
//		    e.printStackTrace();
//		}
//		log.info("old data-id: " + idNumOld);
//		log.info("new data-id: " + idNumNew);
//		int dif = idNumNew - idNumOld;
//		log.info("there are how many new message: " + dif);
//		
//		//由id的差值获取新的message
//		if(dif > 0) {
//			List<String> result = new ArrayList<String>();
//			int id = 0;
//			for (int i=0 ; i<dif ; i++) {
//				id = newEs.size() - 1 - dif + i;
//				log.info("获取第 " + id + " 项元素的文本");
//				result.add(getTextFromElement(newEs.get(id)));
//			}
//			return result;
//		}
//		return null;
//	}

}
